//
//  HJInfoDetailVC.m
//  project
//
//  Created by hu on 2019/3/23.
//  Copyright © 2019 健健. All rights reserved.
//

#import "HJInfoDetailVC.h"
#import "YFDetailDongtaiHeaderView.h"
#import "YFSegmentView.h"
#import "YFScrollView.h"
#import "HJProfileHeaderView.h"
#import "YFJourneyModel.h"
#import "HJChatRoomVC.h"
#import "HJOtherDynamic.h"
#import "HJInfoCell.h"
#import "HJPlayerVC.h"
#import "HJVideoModel.h"

static NSString * const identifier = @"HJInfoCell";

@interface HJInfoDetailVC ()<UIScrollViewDelegate,UICollectionViewDelegate,UICollectionViewDataSource>

@property (nonatomic, strong) YFDetailDongtaiHeaderView *headerView;

@property (nonatomic, strong) YFSegmentView *segmentView;

@property (nonatomic, strong) YFScrollView *containerScrollView;

@property (nonatomic, strong) UIScrollView *pageScrollView;

@property (nonatomic, strong) UITableView *profileTableView;

/**
 动态
 */
@property (nonatomic,strong) UICollectionView * collectionView;
//@property (nonatomic, strong) UITableView *dongtaiTableView;

@property (nonatomic, assign) BOOL ContainerCanScroll;

@property (nonatomic, assign) BOOL tableConScroll;

/**
 资料头部
 */
@property (nonatomic,strong,nonnull) HJProfileHeaderView *profileTableHeaderView;

/**
 数据源
 */
@property (nonatomic,strong,nonnull) NSMutableDictionary * dataDic;
@property (nonatomic,strong) NSMutableArray * dataArray;
@property (nonatomic,strong) NSMutableArray <HJVideoModel *>* videos;
/**
 当前页
 */
@property (nonatomic,assign) NSInteger currentPage;

/**
 总页码
 */
@property (nonatomic,assign) NSInteger pageCount;
/**
 点击index
 */
@property (nonatomic,strong) NSIndexPath  * indexpath;

/**
 私聊
 */
@property (nonatomic,strong) UIButton * chatBtn;

@end



@implementation HJInfoDetailVC

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar setBackgroundImage:UIImage.new forBarMetrics:(UIBarMetricsDefault)];
    NSMutableDictionary *att = [NSMutableDictionary dictionary];
    att[NSForegroundColorAttributeName] = [UIColor colorWithHex:0xffffff];
    [self.navigationController.navigationBar setTitleTextAttributes:att];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController.navigationBar setBackgroundImage:UIColor.whiteColor.image forBarMetrics:(UIBarMetricsDefault)];
    NSMutableDictionary *att = [NSMutableDictionary dictionary];
    att[NSForegroundColorAttributeName] = [UIColor colorWithHex:0x000000];
    [self.navigationController.navigationBar setTitleTextAttributes:att];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(acceptContainerMsg:) name:kHomeLeaveTopNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(accepTabletMsg:) name:kHomeGoTopNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(accepTabletMsg:) name:kHomeLeaveTopNotification object:nil];
    self.navTitle = @"个人资料";
    NSMutableDictionary *att = [NSMutableDictionary dictionary];
    att[NSForegroundColorAttributeName] = [UIColor colorWithHex:0xffffff];
    [self.navigationController.navigationBar setTitleTextAttributes:att];
    [self setupViews];
}

- (void)setupViews {
    self.ContainerCanScroll = YES;
    self.edgesForExtendedLayout = UIRectEdgeAll;
    self.automaticallyAdjustsScrollViewInsets = YES;
    self.extendedLayoutIncludesOpaqueBars = YES;
    if (@available(iOS 11.0, *)) {
        [[UIScrollView appearance] setContentInsetAdjustmentBehavior:UIScrollViewContentInsetAdjustmentNever];
        [UITableView appearance].contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    
    [self.view addSubview:self.containerScrollView];
    self.headerView.userModel = self.userModel;
    [self.containerScrollView addSubview:self.headerView];
    [self.containerScrollView addSubview:self.segmentView];
    [self.containerScrollView addSubview:self.pageScrollView];
    self.containerScrollView.contentSize = CGSizeMake(SCREEN_WIDTH, (SCREEN_WIDTH * 3 / 4) + self.segmentView.height + self.pageScrollView.height);
    
    [self.pageScrollView addSubview:self.collectionView];
    [self.pageScrollView addSubview:self.profileTableView];
    
    self.pageScrollView.contentSize = CGSizeMake(SCREEN_WIDTH * 2, self.pageScrollView.height);
    [self.pageScrollView setContentOffset:CGPointMake(0, 0)];
    
    @weakify(self)
    self.segmentView.buttonClickAction = ^(NSInteger idx) {
        @strongify(self)
        [self.pageScrollView setContentOffset:CGPointMake(idx * SCREEN_WIDTH, 0)];
    };
    self.indexpath = [NSIndexPath indexPathForRow:0 inSection:0];
    self.currentPage = 1;
    self.pageCount = 1;
    [self configRefresh];
    [self loadData];
    
    [self.chatBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        @strongify(self)
        make.bottom.equalTo(self.view.mas_bottom).inset(11+SAFE_AREA_HEIGHT);
        make.centerX.equalTo(self.view);
        make.size.mas_equalTo(CGSizeMake(160, 45));
        [self.chatBtn rounded:UIRectCornerAllCorners radius:22.5];
    }];
    
    
    
}

#pragma mark - UIScrollViewDelegate

static CGFloat preOffsetX = 0;

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGFloat offsetY = scrollView.contentOffset.y;
    CGFloat critical = self.headerView.height - NAVIGATION_BAR_HEIGHT;
    /// containerScrollView
    if (scrollView.tag == 1000) {
        // 导航栏渐变
        CGFloat alpha = 0;
        alpha = offsetY / critical   > 1.f ? 1 : offsetY / critical;
        [self.navigationController.navigationBar setBackgroundImage:[UIColor.whiteColor withAlphaComponent:alpha].image forBarMetrics:(UIBarMetricsDefault)];
        NSMutableDictionary *att = [NSMutableDictionary dictionary];
        if (alpha==1) {
            att[NSForegroundColorAttributeName] = [UIColor colorWithHex:0x000000];
        }else {
            att[NSForegroundColorAttributeName] = [UIColor colorWithHex:0xffffff];
        }
        [self.navigationController.navigationBar setTitleTextAttributes:att];
        if (offsetY >= critical) {
            [[NSNotificationCenter defaultCenter] postNotificationName:kHomeGoTopNotification object:nil userInfo:@{@"canScroll":@"1"}];
            self.ContainerCanScroll =  NO;
            scrollView.contentOffset = CGPointMake(0, critical);
        } else {
            if (!self.ContainerCanScroll) {
                scrollView.contentOffset = CGPointMake(0, critical);
            }
        }
    }
    
    /// dongtaiTableView
    if (scrollView.tag == 1001 || scrollView.tag == 1002) {
        if (!self.tableConScroll) {
            [scrollView setContentOffset:(CGPointZero)];
        }
        if (offsetY < 0) {
            [[NSNotificationCenter defaultCenter] postNotificationName:kHomeLeaveTopNotification object:nil userInfo:@{@"canScroll":@"1"}];
        }
    }
    
    // pageScrollView
    if (scrollView.tag == 2000) {
        CGFloat offsetX = scrollView.contentOffset.x;
        //手势向左滑
        if (offsetX > preOffsetX) {
            if (offsetX == SCREEN_WIDTH) {
                [self.segmentView.profileButton setTitleColor:UIColor.grayColor forState:(UIControlStateNormal)];
                [self.segmentView.dongtaiButton setTitleColor:UIColor.blackColor forState:(UIControlStateNormal)];
                [self.segmentView animateWithBtn:self.segmentView.dongtaiButton];
            }
        }
        /// 手势向右滑
        if (offsetX < preOffsetX) {
            if (offsetX == 0) {
                [self.segmentView.profileButton setTitleColor:UIColor.blackColor forState:(UIControlStateNormal)];
                [self.segmentView.dongtaiButton setTitleColor:UIColor.grayColor forState:(UIControlStateNormal)];
                [self.segmentView animateWithBtn:self.segmentView.profileButton];
            }
        }
        preOffsetX = offsetX;
    }
}

#pragma mark - 通知执行方法
- (void)acceptContainerMsg:(NSNotification *)notification {
    NSDictionary *userInfo = notification.userInfo;
    NSString *canScroll = userInfo[@"canScroll"];
    if ([canScroll isEqualToString:@"1"]) {
        self.ContainerCanScroll = YES;
    }
}

- (void)accepTabletMsg:(NSNotification *)notification {
    NSString *notificationName = notification.name;
    if ([notificationName isEqualToString:kHomeGoTopNotification]) {
        NSDictionary *userInfo = notification.userInfo;
        NSString *canScroll = userInfo[@"canScroll"];
        if ([canScroll isEqualToString:@"1"]) {
            self.tableConScroll = YES;
        }
    } else if ([notificationName isEqualToString:kHomeLeaveTopNotification]) {
        self.tableConScroll = NO;
    }
}

#pragma mark - Lazy Load
-(YFDetailDongtaiHeaderView *)headerView {
    if (!_headerView) {
        _headerView = YFDetailDongtaiHeaderView.headerView;
    }
    return _headerView;
}

- (YFSegmentView *)segmentView {
    if (!_segmentView) {
        _segmentView = YFSegmentView.segmentView;
        _segmentView.frame = CGRectMake(0, self.headerView.bottom+10, SCREEN_WIDTH, 54);
    }
    return _segmentView;
}

- (YFScrollView *)containerScrollView {
    if (!_containerScrollView) {
        _containerScrollView = [[YFScrollView alloc] initWithFrame:[UIScreen mainScreen].bounds];
        _containerScrollView.bounces = NO;
        _containerScrollView.showsVerticalScrollIndicator = NO;
        _containerScrollView.showsHorizontalScrollIndicator = NO;
        _containerScrollView.delegate = self;
        _containerScrollView.tag = 1000;
    }
    return _containerScrollView;
}

- (UIScrollView *)pageScrollView {
    if (!_pageScrollView) {
        _pageScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, self.segmentView.bottom, SCREEN_WIDTH, SCREEN_HEIGTH - NAVIGATION_BAR_HEIGHT - self.segmentView.height)];
//        _pageScrollView.backgroundColor = UIColor.redColor;
        _pageScrollView.pagingEnabled = YES;
        _pageScrollView.bounces = NO;
        _pageScrollView.showsVerticalScrollIndicator = NO;
        _pageScrollView.showsHorizontalScrollIndicator = NO;
        _pageScrollView.delegate = self;
        _pageScrollView.tag = 2000;
    }
    return _pageScrollView;
}

- (UITableView *)profileTableView {
    if (!_profileTableView) {
        _profileTableView = [[UITableView alloc] initWithFrame:CGRectMake(self.collectionView.right, self.collectionView.top, SCREEN_WIDTH, self.collectionView.height) style:(UITableViewStylePlain)];
//        _profileTableView.delegate = self;
        _profileTableView.tableFooterView = UIView.new;
        _profileTableView.backgroundColor = UIColor.clearColor;
        _profileTableView.tableHeaderView = self.profileTableHeaderView;
        _profileTableView.tableHeaderView.height = 200;
        _profileTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _profileTableView.tag = 1002;
    }
    return _profileTableView;
}
-(UICollectionView *)collectionView {
    if (!_collectionView) {
        UICollectionViewFlowLayout * layout = [UICollectionViewFlowLayout new];
        layout.itemSize = CGSizeMake((SCREEN_WIDTH-57)/2, 275);
        layout.minimumLineSpacing = 8.5;
        layout.minimumInteritemSpacing = 0;
        layout.sectionInset = UIEdgeInsetsMake(10, 19, 10, 19);
        layout.headerReferenceSize =CGSizeMake(SCREEN_WIDTH, 40);
        
        _collectionView = [[UICollectionView alloc]initWithFrame:self.pageScrollView.bounds collectionViewLayout:layout];
        _collectionView.backgroundColor = UIColor.clearColor;
        _collectionView.tag = 1001;
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.emptyView = self.tipEmptyView;
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.showsHorizontalScrollIndicator = NO;
//        _collectionView.scrollIndicatorInsets = UIEdgeInsetsMake(0, 0, SAFE_AREA_HEIGHT, 0);
        _collectionView.contentInset = UIEdgeInsetsMake(0, 0, 13, 0);
        [_collectionView registerNib:[UINib nibWithNibName:identifier bundle:nil] forCellWithReuseIdentifier:identifier];
        [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header"];
        [self.pageScrollView addSubview:_collectionView];
    }
    return _collectionView;
}

//-(UITableView *)dongtaiTableView {
//    if (!_dongtaiTableView) {
//        _dongtaiTableView = [[UITableView alloc] initWithFrame:self.pageScrollView.bounds style:(UITableViewStylePlain)];
//        _dongtaiTableView.tableFooterView = UIView.new;
//        _dongtaiTableView.backgroundColor = UIColor.clearColor;
//        _dongtaiTableView.tag = 1001;
//        _dongtaiTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
//        _dongtaiTableView.delegate = self;
//        _dongtaiTableView.dataSource = self;
//        _dongtaiTableView.emptyView = self.tipEmptyView;
//        _dongtaiTableView.scrollIndicatorInsets = UIEdgeInsetsMake(0, 0, SAFE_AREA_HEIGHT, 0);
//        [self.pageScrollView addSubview:_dongtaiTableView];
//    }
//    return _dongtaiTableView;
//}

#warning mark -- 资料
-(HJProfileHeaderView *)profileTableHeaderView {
    if (!_profileTableHeaderView) {
        _profileTableHeaderView = [HJProfileHeaderView profileHeader];
        _profileTableHeaderView.userModel = self.userModel;
        @weakify(self)
        _profileTableHeaderView.block = ^(YFUserModel * _Nonnull model) {
            @strongify(self)
            HJChatRoomVC * chatRoomVC = [[UIStoryboard storyboardWithName:@"Chat" bundle:nil]instantiateViewControllerWithIdentifier:chatRoom];
            RCConversationModel * conversationModel = [[RCConversationModel alloc]init];
            conversationModel.conversationTitle = model.nickName;
            conversationModel.conversationType = ConversationType_PRIVATE;
            conversationModel.targetId = model.userId;
            chatRoomVC.conversationModel = conversationModel;
            [self.navigationController pushViewController:chatRoomVC animated:YES];
        };
    }
    return _profileTableHeaderView;
}
-(UIButton *)chatBtn {
    if (!_chatBtn) {
        _chatBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_chatBtn setTitle:@"私聊" forState:0];
        _chatBtn.titleLabel.font = [UIFont fontWithName:PingFangSC_Medium size:17];
        [_chatBtn setBackgroundColor:[UIColor colorWithHex:0xff2400]];
        @weakify(self)
        [[_chatBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            @strongify(self)
            HJChatRoomVC * chatRoomVC = [[UIStoryboard storyboardWithName:@"Chat" bundle:nil]instantiateViewControllerWithIdentifier:chatRoom];
            RCConversationModel * conversationModel = [[RCConversationModel alloc]init];
            conversationModel.conversationTitle = self.userModel.nickName;
            conversationModel.conversationType = ConversationType_PRIVATE;
            conversationModel.targetId = self.userModel.userId;
            chatRoomVC.conversationModel = conversationModel;
            [self.navigationController pushViewController:chatRoomVC animated:YES];
        }];
        [self.view insertSubview:_chatBtn aboveSubview:self.pageScrollView];
    }
    return _chatBtn;
}

#warning mark -- 动态
-(NSMutableArray *)dataArray {
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

//#pragma mark - UITableViewDataSource, UITableViewDelegate
//- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
//    if (tableView == self.dongtaiTableView) {
//        return self.dataArray.count;
//    }
//    return 0;
//}
//
//- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//    if (tableView == self.dongtaiTableView) {
//        YFMyDongtaiCell * dongtaiCell =[tableView cellForRowAtIndexPath:indexPath];
//        if (!dongtaiCell) {
//            dongtaiCell = [[NSBundle mainBundle] loadNibNamed:identifier owner:nil options:nil].firstObject;
//        }
//        dongtaiCell.viewModel = self.dataArray[indexPath.row];
//        dongtaiCell.moreButton.hidden = YES;
//
//        return dongtaiCell;
//    }
//    return [UITableViewCell new];
//}
//
//- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
//    if (tableView == self.dongtaiTableView) {
//        return self.dataArray[indexPath.row].cellHeight;
//    }
//    return 0;
//}
//-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
//    if (tableView == self.dongtaiTableView) {
//    }
//}


-(void)configRefresh {
    @weakify(self)
    MJRefreshNormalHeader * header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        @strongify(self)
        self.currentPage = 1;
        [self.dataDic removeAllObjects];
        [self.videos removeAllObjects];
        [self loadData];
    }];
    self.collectionView.mj_header = header;
    
    MJRefreshBackNormalFooter * footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        @strongify(self)
        self.currentPage += 1;
        if (self.currentPage > self.pageCount) {
            [self.collectionView.mj_footer endRefreshingWithNoMoreData];
        } else {
            [self loadData];
        }
    }];
    self.collectionView.mj_footer = footer;
}

-(NSMutableDictionary *)dataDic {
    if (!_dataDic) {
        _dataDic = [NSMutableDictionary dictionary];
    }
    return _dataDic;
}
-(NSMutableArray<HJVideoModel *> *)videos {
    if (!_videos) {
        _videos = [NSMutableArray array];
    }
    return _videos;
}

-(void)loadData {
    NSString * url = [Api stringByAppendingString:MyDongtaiApi];
    NSMutableDictionary * params = [NSMutableDictionary dictionary];
    params[@"currentAlbumUserId"] = self.userModel.userId;
    params[@"pageCurrent"] = @(self.currentPage);
    [HJHttpTool post:url params:params success:^(HJResponeds *result) {
        self.pageCount = [result.data[@"pages"] integerValue];
        NSArray * arr = [NSArray yy_modelArrayWithClass:[HJVideoModel class] json:result.data[@"records"]];
        [self.videos addObjectsFromArray:arr];
        NSMutableArray<HJVideoModel *> *VMs = [NSMutableArray arrayWithCapacity:arr.count];
        for (HJVideoModel *dongtaiModel in arr) {
            NSString * key;
            if (dongtaiModel.time && dongtaiModel.time.length > 10) {
                key = [dongtaiModel.time substringToIndex:10];
            }
            if ([[self.dataDic allKeys] containsObject:key]) {// 包含
                VMs = [self.dataDic objectForKey:key];
                [VMs addObject:dongtaiModel];
                [self.dataDic setObject:VMs forKey:key];
            }else {// 不包含
                VMs = [[NSMutableArray alloc]initWithObjects:dongtaiModel, nil];
                [self.dataDic setObject:VMs forKey:key];
                [self.dataArray addObject:key];
            }
        }
        [self.collectionView endRefresh];
        [self.collectionView reloadData];
    } failure:^(id result) {
        [self.collectionView endRefresh];
        [self showErrorHUDWithError:result];
    }];
}

#pragma mark -- UICollectionViewDelegate,UICollectionViewDataSource
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return self.dataDic.allKeys.count;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return [self.dataDic[self.dataArray[section]] count];
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    HJInfoCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
    [cell loadDataMoreWithModel:self.dataDic[self.dataArray[indexPath.section]][indexPath.row]];
    
    return cell;
}
-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    UICollectionReusableView * reusableView = nil;
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        reusableView = (UICollectionReusableView *)[collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header" forIndexPath:indexPath];
        reusableView.backgroundColor = [UIColor clearColor];
        for (UIView * view in reusableView.subviews) {
            [view removeFromSuperview];
        }
        
        UILabel * timeLabel = [UILabel new];
        timeLabel.text = self.dataArray[indexPath.section];
        timeLabel.font = [UIFont fontWithName:PingFangSC_Medium size:15];
        timeLabel.textColor = [UIColor colorWithHex:0x292929];
        [reusableView addSubview:timeLabel];
        [timeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(@19);
            make.bottom.equalTo(reusableView.mas_bottom);
            make.size.mas_equalTo(CGSizeMake(reusableView.width-38, 16));
        }];
    }
    return reusableView;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
//    HJVideoModel * model = self.dataDic[self.dataArray[indexPath.section]][indexPath.row];
    HJPlayerVC * playVC = [HJPlayerVC new];
    playVC.isPush = YES;
    playVC.indexPath = indexPath;
    playVC.dataArray = self.videos;
    [self.navigationController pushViewController:playVC animated:YES];
    
//    HJOtherDynamic * dynamicVC = [HJOtherDynamic new];
//    dynamicVC.cellModel = self.dataDic[self.dataArray[indexPath.section]][indexPath.row];
//    self.indexpath = indexPath;
//    @weakify(self)
//    dynamicVC.didBackBtnClicked = ^(NSString * _Nonnull zanNum, BOOL isSelecte) {
//        @strongify(self)
//        YFMineCellViewModel * model = self.dataDic[self.dataArray[indexPath.section]][indexPath.row];
//        model.praiseAmount = zanNum;
//        model.isPraise = isSelecte;
//        [self.collectionView reloadData];
//    };
//    [self.navigationController pushViewController:dynamicVC animated:YES];

}

@end



